package com.example.smartf.repository.mongoDB.Impl;

import com.example.smartf.repository.mongoDB.MongoUserUtil;
import com.example.smartf.model.mongo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MongoUserUtilImpl implements MongoUserUtil {
    @Autowired
    MongoTemplate mongoTemplate;

    public User findByUsername(String username) {

        Query query = new Query(Criteria.where("username").is(username));
        return mongoTemplate.findOne(query,User.class,"User");
    }

    public List<User> findByDeviceID(String deviceID){
        Query query = new Query(Criteria.where("devices").is(deviceID));
        return mongoTemplate.find(query,User.class,"User");
    }


    public User addUser(User user){
        return mongoTemplate.save(user,"User");
    }

    public void updateUser(User user){
        Query query = new Query(Criteria.where("username").is(user.getUsername()));
        Update update = new Update().set("devices",user.getDevices());
        mongoTemplate.updateFirst(query,update,User.class,"User");
    }

}
